const Service = require('egg').Service;

module.exports = app => {
  return class UserService extends Service {
    async list(pageNo = 1, pageSize = app.config.pageBean.pageSize, order_by = 'create_time', order = 'ASC', where = {}, attributes) {
      return await this.ctx.model.User.findAndCountAll({
          where: where,
          offset: (+pageNo - 1) * +pageSize,
          limit: +pageSize,
          attributes,
          order: [[order_by, order.toUpperCase()]],
        });
    }

    async find(user_id) {
      const user = await this.ctx.model.User.findOne({
        where: {
          user_id
        },
      });
      if (!user) {
        this.ctx.throw(404, 'user not found');
      }
      return user.dataValues;
    }

    async create(user) {
      return await this.ctx.model.User.create(user);
    }
    
    async update(user_id, updates) {
      const user = await this.ctx.model.User.findOne({
        where: {
          user_id
        },
      });
      if (!user) {
        this.ctx.throw(404, 'user not found');
      }
      return await user.update(updates);
    }

    async del(user_id) {
      const user = await this.ctx.model.User.findOne({
        where: {
          user_id
        },
      });
      if (!user) {
        this.ctx.throw(404, 'user not found');
      }
      return user.destroy();
    }
  }
}